package cn.matezk.lianlian.task;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.cloud.WxCloudDatabaseQueryResult;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.matezk.lianlian.dao.UserDao;
import cn.matezk.lianlian.model.User;
import com.xxl.job.core.handler.annotation.XxlJob;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class UserSyncTask {
    @Autowired
    private WxMaService wxMaService;
    @Autowired
    private UserDao userDao;

    @XxlJob("userSyncTask")
    public void execute() throws WxErrorException {
        WxCloudDatabaseQueryResult  queryResult = wxMaService.getCloudService().query("user", null, null, 0, 100);
        String data[] = queryResult.getData();
        for (String u : data) {
            JSONObject obj = JSONUtil.parseObj(u);
            String unionId = obj.getStr("union_id");
            if (ObjectUtil.isEmpty(unionId))    continue;
            User user = userDao.selectByPrimaryKey(unionId);
            if (ObjectUtil.isNull(user)) {
                user = new User();
                user.setUnionId(unionId);
                user.setUserId(obj.getStr("user_id"));
                user.setIsSub(obj.getBool("is_sub"));
                user.setWechatNotifyEnable(obj.getBool("push_enable"));
                user.setOpenId(obj.getStr("open_id"));
                userDao.insertSelective(user);
            } else {
                user.setUserId(obj.getStr("user_id"));
                user.setIsSub(obj.getBool("is_sub"));
                user.setWechatNotifyEnable(obj.getBool("push_enable"));
                user.setOpenId(obj.getStr("open_id"));
                userDao.updateByOpenIdSelective(user);
            }
        }
    }
}
